/*
 * MoveItemsRunnable.java
 * 
 * Copyright 2007, 2008 Tiberiumlabs
 *
 * This file is part of Tiberiumlabs Lailaps.
 *
 * Tiberiumlabs Lailaps is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tiberiumlabs Lailaps is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tiberiumlabs.lailaps.gui.transfer;

import java.util.Arrays;
import org.tiberiumlabs.lailaps.Mediator;
import org.tiberiumlabs.lailaps.actions.events.DataEvent;
import org.tiberiumlabs.lailaps.list.DownloadsListModel;
import org.tiberiumlabs.lailaps.threads.ThreadsMap;

/**
 *
 * @author <a href="mailto:paranoid.tiberiumlabs@gmail.com">Paranoid</a>
 */
public class MoveItemsRunnable implements Runnable {
    
    private static final DownloadsListModel model = Mediator.getMediator().getDownloadsListModel();
    private static final ThreadsMap threadsMap = Mediator.getMediator().getThreadsMap();
    
    private int index = -1;
    private int[] rows = null;

    public MoveItemsRunnable(int index, int[] rows) {
        this.index = index;
        this.rows = rows;
    }

    @Override
    public void run() {
        
        // need to sort before, to count rows correctly
        Arrays.sort(rows);
        
        // actual move in model. model is NOT thread safe, so access it only from ActionFactory
        model.moveItems(index, rows);
        
        // now need to create DataEvent to notify threads.
        // choose first row number that we touched
        int firstRow = rows[0] <= index ? rows[0] : index;
        // choose last row number that we touched
        int lastRow = rows[rows.length - 1] >= index ? rows[rows.length - 1] : index;
        
        threadsMap.notify(new DataEvent(DataEvent.MOVED, firstRow, lastRow, rows.length));
        
    }

}
